package com.eightbears.beboy.ui.merchant.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopSetMealEditAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.ShopSetMealEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_DELETEMEAL;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_MEALLIST;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.merchant.activity.ShopSetMealEditActivity.EVENT_EDIT_SET_MEAL_SUCCESS;

public class ShopSetMealActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String PARAMS_SET_MEAL_ENTITY = "setMealENTITY";

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    View view_empty;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    private ShopSetMealEditAdapter shopSetMealEditAdapter;
    private ShopSetMealEntity.SetMeal shopSetMealEntity;
    private UserEntity.Shop shopInfo;
    private DefaultDialog.Builder mBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_set_meal);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_set_meal_manage);
        shopInfo = SPUtil.getUser().getData().getShops().get(0);
        initAdapter();

    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        shopSetMealEditAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                shopSetMealEntity = (ShopSetMealEntity.SetMeal) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.ll_edit:
                        startLocalActivity(ShopSetMealActivity.this, ShopSetMealEditActivity.class,
                                PARAMS_SET_MEAL_ENTITY, shopSetMealEntity);
                        break;
                    case R.id.ll_delete:
                        showDeleteDialog();
                        break;
                }
            }
        });
    }

    private void showDeleteDialog() {
        if (mBuilder == null) {
            mBuilder = new DefaultDialog.Builder(ShopSetMealActivity.this);
            mBuilder.setTitle(getString(R.string.alert_text))
                    .setMessage(getString(R.string.text_delete_set_meal))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getDeleteMealData();
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
        }
        mBuilder.create().show();
    }

    @OnClick(R.id.ll_back)
    void ll_back() {
        finish();
    }

    @OnClick(R.id.btn_add_set_meal)
    void addSetMeal() {
        startLocalActivity(ShopSetMealActivity.this, ShopSetMealEditActivity.class);
    }


    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        shopSetMealEditAdapter = new ShopSetMealEditAdapter();
        shopSetMealEditAdapter.openLoadAnimation();
        shopSetMealEditAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(shopSetMealEditAdapter);
    }

    private void getData() {
        String url = URL_SHOPS_MEALLIST + shopInfo.getShop_id() + "/coupons";
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", PARAMS_PAGE_SIZE)
                .addParams("is_manager", "1")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                ShopSetMealEntity shopSetMealEntity = GsonUtil.fromJson(response, ShopSetMealEntity.class);
                if (shopSetMealEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    shopSetMealEditAdapter.setNewData(shopSetMealEntity.getData().getList());
                    isEnd = shopSetMealEntity.getData().getIs_end();
                    if (page == 1) {
                        if (shopSetMealEntity.getData().getList().size() == 0) {
                            view_empty.setVisibility(View.VISIBLE);
                        } else {
                            view_empty.setVisibility(View.GONE);
                            shopSetMealEditAdapter.setNewData(shopSetMealEntity.getData().getList());
                        }
                    } else {
                        shopSetMealEditAdapter.addData(shopSetMealEntity.getData().getList());
                        shopSetMealEditAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopSetMealActivity.this, status_error);
            }

        });
    }

    public void getDeleteMealData() {
        OkHttpUtils.delete().url(URL_SHOPS_DELETEMEAL + shopSetMealEntity.getId())
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.alert_delete_success));
                shopSetMealEditAdapter.getData().remove(shopSetMealEntity);
                shopSetMealEditAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopSetMealActivity.this, status_error);
            }
        });
    }

    @Override
    public void onRefresh() {
        shopSetMealEditAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                shopSetMealEditAdapter.getData().clear();
                getData();
                shopSetMealEditAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    shopSetMealEditAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        ShowToast.showShortToast(R.string.network_anomalies);
                        shopSetMealEditAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_EDIT_SET_MEAL_SUCCESS:
                onRefresh();
                break;
        }
    }
}
